package com.ailk.aee.pcc.dao;

import com.ailk.aee.pcc.mongo.Mongo;
import com.ailk.aee.pcc.utils.CacheUtils;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 用户指标数据处理
 *
 * @author pengzhang
 */
@Component
public class UserTargetDao {

    Mongo userTargetMongo;

    Mongo userTargetBIMongo;


    /**
     * 查询用户标指值
     *
     * @param userId     用户ID
     * @param targetName 指标名
     *
     * @return
     */
    public DBObject queryUserTarget(String userId, String targetName, String channelName) {
        BasicDBObject basicDBObject = new BasicDBObject(targetName, 1);

        DBCollection collection = "BI".equalsIgnoreCase(channelName) ?
                userTargetBIMongo.getContentCollection() : userTargetMongo.getContentCollection();

        return collection.findOne(new BasicDBObject("userId", userId), basicDBObject);
    }

    /**
     * 新增用户指标
     *
     * @param userId
     * @param targetName
     * @param value
     * @param channelName
     *
     * @return
     */
    public void addUserTarget(String userId, String targetName, String value, String channelName) {

        BasicDBObject query = new BasicDBObject("userId", userId);
        BasicDBObject update = new BasicDBObject("$set", new BasicDBObject(targetName, value));

        DBCollection collection = "BI".equalsIgnoreCase(channelName) ?
                userTargetBIMongo.getContentCollection() : userTargetMongo.getContentCollection();

        collection.update(query, update, true, false);
    }

    /**
     * 删除 用户指标
     *
     * @param userId
     * @param channelName
     */
    public void deleteUserTarget(String userId, String channelName) {

        DBCollection collection = "BI".equalsIgnoreCase(channelName) ?
                userTargetBIMongo.getContentCollection() : userTargetMongo.getContentCollection();

        collection.remove(new BasicDBObject("userId", userId));
    }

    /**
     * 批量设置用户指标
     *
     * @param targetKeys 指标名集合，格式为 "userid|channelName|targetKey1|targetKey2|targetKey3|..."
     * @param value      指标值
     */
    public void addBatchUserTarget(String targetKeys, String value) {

        String[] split = targetKeys.split("\\|");
        String channelName = split[1];
        BasicDBObject basicDBObject = new BasicDBObject("userId", split[0]);
        BasicDBObject params = new BasicDBObject();

        for (int i = 2; i < split.length; i++) {
            params.put(CacheUtils.getTargetCacheName(channelName, split[i]), value);
        }

        DBCollection collection = "BI".equalsIgnoreCase(channelName) ?
                userTargetBIMongo.getContentCollection() : userTargetMongo.getContentCollection();

        collection.update(basicDBObject, new BasicDBObject("$set", params), true, false);
    }
}
